#include <stdio.h>
#include "sqlite3.h"
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include "sqlite_select.h"

float sqlite_select(sqlite3 *db,char *ID,char *time)
{
	int       rv=-1;
	int       i=-1;
	int       j=-1;
	void      *data;
	char      sql[128]={};
	char      *errmsg=NULL;
	float     temp;

	int       nRow=0;
	int       nColumn=0;
	char      **dbResult=NULL;
	int       index=0;
	char      buf[128]={};
	char      buf_2[128]={};
	char      buf_3[128]={};
	char      buf_4[32]={};
	char      *ptr=NULL;
	char      *str=NULL;
	char      *rtr=NULL;
	char      *ntr=NULL;


	sprintf(sql,"select * from temp LIMIT 0,1");
	rv=sqlite3_get_table(db, sql, &dbResult, &nRow, &nColumn, &errmsg);
	if(rv!=SQLITE_OK)
	{
		printf("select failure[1]:%s\n", errmsg);
		return -1;
	}
	if(nRow>0)
	{
		index=nColumn;
		for(i=0;i<nRow;i++)
		{
			for(j=0;j<nColumn;j++)
			{
				printf("%s %s\n",dbResult[j],dbResult[index]);
				strcat(buf,"/");
				strcat(buf,(char *)dbResult[index]);
				printf("buf[1]:%s\n", buf);
				index++;
			}
		}
		printf("buf[2]:%s\n", buf);
		ptr=strstr(buf,"/");
		if(!ptr)
		{
			printf("seek '/'failure:%s\n",strerror(errno));
			return -2;
		}
		printf("ptr:%s\n",ptr+=1);
		sprintf(buf_2,ptr);
		printf("buf_2:%s\n",buf_2);

		str=strstr(buf_2,"/");
		if(!str)
		{
			printf("seek '/'failure:%s\n",strerror(errno));
			return -3;
		}
		printf("str:%s\n",str+=1);
		sprintf(buf_3,str);
		printf("buf_3:%s\n",buf_3);
		
		rtr=strstr(buf_3,"/");
		if(!rtr)
		{
			printf("seek '/'failure:%s\n",strerror(errno));
			return -4;
		}
		printf("rtr:%s\n",rtr+=1);
		sprintf(buf_4,rtr);
		printf("buf_4:%s\n",buf_4);
		
		ntr=strstr(buf_4,"/");
		if(!ntr)
		{
			printf("seek '/'failure:%s\n",strerror(errno));
			return -5;
		}
		printf("ntr:%s\n",ntr+=1);
	
		strncpy(ID,str,strlen(str)-strlen(rtr-=1));
		strncpy(time,rtr,strlen(rtr+=1)-strlen(ntr-=1));
		printf("ID:%s time:%s temp:%s\n", ID, time, ntr+=1);
		temp=atof(ntr);
		printf("temp(atof):%f\n",temp);
	
		memset(buf_2, 0, sizeof(buf));
		memset(buf_3, 0, sizeof(buf));
	}
	else
	{
		ID=0;
		time=0;
		temp=0;
	}
	return temp;

}
